package com.xkdx.guangguang.fragment.newsinfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.ShopAndBrandNewProduct;

public class NewsFragment extends BaseFragment implements OnGestureListener,
		OnTouchListener {
	View view;
	ViewFlipper viewFlipper;
	TextView title, content, mark;
	Button back, share, purchase;
	String infoID;
	List<String> list;
	GestureDetector detector;
	LayoutInflater inflater;
	ShopAndBrandNewProduct shopNewProduct;
	DisplayMetrics metrics;
	int Image_height;
	Context context;
	int number = 1;
	int sharePictureWhich = 0;
	List<View> views = new ArrayList<View>();
	ImageLoader imageLoader = ImageLoader.getInstance();
	DisplayImageOptions options;
	LayoutParams lp;
	NewsAction newsAction;
	NewsModule newsModule;
	NewsPresistence newsPresistence;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		inflater = LayoutInflater.from(getActivity());
		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.empty_photo)
				.showImageOnFail(R.drawable.empty_photo)
				.resetViewBeforeLoading().cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACTLY)
				.bitmapConfig(Bitmap.Config.RGB_565)
				.displayer(new FadeInBitmapDisplayer(300)).build();

		infoID = getArguments().getString("infoID");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.newproduct_info, container, false);
		findView();
		setOnClick();
		showLoading();
		return view;
	}

	@Override
	public void findView() {
		viewFlipper = (ViewFlipper) view
				.findViewById(R.id.new_product_info_viewflipper);
		lp = viewFlipper.getLayoutParams();
		title = (TextView) view.findViewById(R.id.new_product_info_title);
		content = (TextView) view.findViewById(R.id.new_product_info_content);
		mark = (TextView) view.findViewById(R.id.new_product_info_mark);
		back = (Button) view.findViewById(R.id.new_product_info_back);
		share = (Button) view.findViewById(R.id.new_product_info_share);
		viewFlipper.setOnTouchListener(this);
		viewFlipper.setLongClickable(true);
		detector = new GestureDetector(this);
		newsAction = new NewsAction(infoID);
		newsModule = new NewsModule();

	}

	@Override
	public void setOnClick() {
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (IConstants.isHasPush && !IConstants.isHasSelfPush) {
					IConstants.isHasPush = false;
					getActivity().finish();
				} else if (IConstants.isHasSelfPush) {
//					IConstants.isHasSelfPush = false;
					getActivity().finish();
				} else {
					getFragmentManager().popBackStack();
				}
			}
		});

		// 分享按钮实现
		share.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setShare();
			}

		});

	}

	private void loadImage(final ProgressBar pb, ImageView im, int i) {

		imageLoader.displayImage(IConstants.addSuffix(list.get(i), "_L"), im,
				options, new SimpleImageLoadingListener() {
					@Override
					public void onLoadingStarted(String imageUri, View view) {
						pb.setVisibility(View.VISIBLE);
					}

					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						pb.setVisibility(View.GONE);
					}

					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						pb.setVisibility(View.GONE);
					}
				});

	}

	@Override
	public void showLoading() {
		dataLoadDialog.show();
		newsPresistence = new NewsPresistence(this);
		newsPresistence.setActitons(newsAction);
		newsPresistence.setModule(newsModule);
		newsPresistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (newsPresistence != null) {
					newsPresistence.cancel(true);
				}
				getFragmentManager().popBackStack();

			}
		});
		dataLoadDialog.show();

	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();
		if (map.containsKey("0")) {
			shopNewProduct = newsModule.shopAndBrandNewProduct;
			setValuse();
		} else {
			refresh(map);
		}

	}

	private void setValuse() {
		list = shopNewProduct.getPictureUrlList();
		for (int i = 0; i < list.size(); i++) {
			View view = inflater.inflate(R.layout.new_pro_im, null);
			view.setLayoutParams(lp);
			ProgressBar pb = (ProgressBar) view.findViewById(R.id.new_pro_pb);
			ImageView im = (ImageView) view.findViewById(R.id.new_pro_im);
			loadImage(pb, im, i);
			viewFlipper.addView(view);
			// Log.i("NewProduct", "收到消息");
		}
		if (list.size() != 0) {
			mark.setText(1 + "/" + list.size());
		}
		title.setText(shopNewProduct.getInfoTitle());
		content.setText(shopNewProduct.getInfoContent());

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (list == null || list.size() <= 1) {
			return false;
		}
		return detector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() - e2.getX() > 120) {

			viewFlipper.setInAnimation(AnimationUtils.loadAnimation(
					getActivity(), R.anim.left_in));
			;
			viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
					getActivity(), R.anim.left_out));
			viewFlipper.showNext();
			number += 1;
			if (number > list.size()) {
				number = 1;
			}
			mark.setText(number + "/" + list.size());
			sharePictureWhich = number - 1;
			return true;
		} else if (e1.getX() - e2.getX() < -120) {
			viewFlipper.setInAnimation(AnimationUtils.loadAnimation(
					getActivity(), R.anim.right_in));
			viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(
					getActivity(), R.anim.right_out));
			viewFlipper.showPrevious();
			number -= 1;
			if (number < 1) {
				number = list.size();
			}
			mark.setText(number + "/" + list.size());
			sharePictureWhich = number - 1;
			return true;
		}
		return false;
	}

	private void setShare() {
		String path = IConstants.addSuffix(list.get(number - 1), "_L");
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.setType("image/*");
		Uri uri = Uri.parse(path);
		List<ResolveInfo> resInfo = getActivity().getPackageManager()
				.queryIntentActivities(intent, 0);

		if (!resInfo.isEmpty()) {
			List<Intent> targetedShareIntents = new ArrayList<Intent>();
			for (ResolveInfo info : resInfo) {
				Intent targeted = new Intent(Intent.ACTION_SEND);
				targeted.setType("image/*");
				intent.setType("text/plain");
				ActivityInfo activityInfo = info.activityInfo;

				if (activityInfo.packageName.contains("bluetooth")
						|| activityInfo.name.contains("bluetooth")) {
					continue; // 过滤蓝牙应用
				}

				if (activityInfo.packageName.contains("gm")
						|| activityInfo.name.contains("mail")) {
					targeted.putExtra(Intent.EXTRA_TEXT, content.getText());
					targeted.putExtra(Intent.EXTRA_STREAM, uri);
				} else if (activityInfo.packageName.contains("zxing")) {
					targeted.putExtra(Intent.EXTRA_TEXT, content.getText());
					targeted.putExtra(Intent.EXTRA_STREAM, uri);
				} else {
					targeted.putExtra(Intent.EXTRA_TEXT, content.getText());
					targeted.putExtra(Intent.EXTRA_STREAM, uri);
				}
				targeted.setPackage(activityInfo.packageName);
				targetedShareIntents.add(targeted);
			}
			// 分享框标题
			Intent chooserIntent = Intent.createChooser(
					targetedShareIntents.remove(0), "选择程序分享");
			if (chooserIntent == null) {
				return;
			}

			chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
					targetedShareIntents.toArray(new Parcelable[] {}));
			try {
				startActivity(chooserIntent);
			} catch (android.content.ActivityNotFoundException ex) {
				Toast.makeText(getActivity(), "没找到分享的应用", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

}
